package com.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pojo.News;
import com.pojo.NewsList;
import com.service.ToFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/files")
public class ToFiles {

    @Autowired
    public ToFileService service;


    @Autowired
    ObjectMapper objectMapper;

    @GetMapping("/tofiles")
    public String tofile() throws IOException {

        // 存放的位置
        String path = "F:\\idea项目\\ChangDeNews";
        String typeDec = "null";
        for (int i = 1; i < 8; i++) {
            List<NewsList> top30 = service.findTop30(i);

            for (NewsList newsList : top30) {
                String replace = newsList.getUrl().replace("http://nyncj.changde.gov.cn", "");
                newsList.setUrl(replace);
            }

            switch (i) {
                case 1:
                    typeDec = "常德动态";
                    break;
                case 2:
                    typeDec = "乡村振兴";
                    break;
                case 3:
                    typeDec = "农事指导";
                    break;
                case 4:
                    typeDec = "现代农业";
                    break;
                case 5:
                    typeDec = "质量安全";
                    break;
                case 6:
                    typeDec = "三农论坛";
                    break;
                case 7:
                    typeDec = "领导言论";
                    break;
            }

            File file = new File(path, typeDec + ".json");
            if (!file.exists()) {
                file.createNewFile();
            }
            objectMapper.writeValue(file, top30);
        }
        return "ToFile success";
    }
}
